package com.aliyun.www.sync.core;

import com.google.common.io.BaseEncoding;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author kyle
 * @date 2018/08/17
 */
public class Sign {

	public static String sign(String str, String privateKey) {
		return sign(str, privateKey, "utf-8", "SHA256WithRSA");
	}

	public static String sign(String content, String privateKey, String encode, String signMethod) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(BaseEncoding.base64().decode(privateKey));

			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature.getInstance(signMethod);

			signature.initSign(priKey);
			signature.update(content.getBytes(encode));

			byte[] signed = signature.sign();

			return BaseEncoding.base64().encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
